package util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class CookieUtil {

    public static final int MAX_AGE=365*24*60*60;
    public static final String CHARSET="utf-8";

    public static void addCookie(String key, String value, HttpServletResponse response){
        addCookie(key,value,MAX_AGE,null,response);
    }

    public static void addCookie(String key, String value, int maxAge, HttpServletResponse response){
        addCookie(key,value,maxAge,null,response);
    }

    public static void addCookie(String key, String value, int maxAge, String path, HttpServletResponse response){
        try {
            Cookie cookie=new Cookie(key, URLEncoder.encode(value,CHARSET));

            cookie.setMaxAge(maxAge);

            if(path!=null){
                cookie.setPath(path);
            }

            response.addCookie(cookie);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }


    public static String findCookie(String key, HttpServletRequest request){
        Cookie[] cookies=request.getCookies();

        if(cookies!=null){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals(key)){
                    try {
                        return URLDecoder.decode(cookie.getValue(),CHARSET);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }





    public static void removeCookie(String key, String path, HttpServletResponse response){
        Cookie cookie=new Cookie(key, "");

        cookie.setMaxAge(0);

        if(path!=null){
            cookie.setPath(path);
        }

        response.addCookie(cookie);

    }





    public static void removeCookie(String key,  HttpServletResponse response){
        Cookie cookie=new Cookie(key, "");

        cookie.setMaxAge(0);

        response.addCookie(cookie);

    }








}
